package handlers

import (
	"app-market-pub/cache"
	"app-market-pub/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	address := c.PostForm("address")
	if title == "" || content == "" || address == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := models.App{
		Title:   title,
		Content: content,
		Address: address,
	}
	tx := models.DB.Begin()
	err := tx.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	tx.Commit()

	redis_key := "app_add_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(data)
	var app models.App
	models.DB.Where("id=?", data.ID).First(&app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}

func TypeAdd(c *gin.Context) {
	name := c.PostForm("name")

	data := models.Types{
		Name: name,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}
func List(c *gin.Context) {
	var types []models.Types

	redis_key := "types_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&types)
		jsonData, _ := json.Marshal(types)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &types)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": types,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var app models.App
	redis_key := "types_list_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
	return
}
